import { Injectable, ErrorHandler } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { CookieService } from 'ngx-cookie';

// 基础服务类，提供基础路径
@Injectable()
export class BaseService {

	// 当前sso的服务，和web前端地址一至
	service:string = "http://58.16.67.49:9050/bhqoa/";
	// 附件服务器地址，和web前端地址一至
	fileUrl:string = "http://58.16.67.49:9050/bhqoa/";
	// 基础数据服务地址，为tomcat服务端地址，不带/rest
	hostUrl:string = "http://58.16.67.49:9050/bhqoa_server";
	// 数据服务地址，为tomcat服务端地址
	baseUrl:string = "http://58.16.67.49:9050/bhqoa_server/rest";

	// // 当前sso的服务，和web前端地址一至
	// service:string = "http://localhost:8017/";
	// // 附件服务器地址，和web前端地址一至
	// fileUrl:string = "http://localhost:8017/";
	// // 基础数据服务地址，为tomcat服务端地址，不带/rest
	// hostUrl:string = "http://localhost:9090/bhqoa";
	// // 数据服务地址，为tomcat服务端地址
	// baseUrl:string = "http://localhost:9090/bhqoa/rest";

	constructor(
		private errorHandler:ErrorHandler,
		private _cookieService:CookieService,) { 
	}

	httpOptions():HttpHeaders{
		let headers:HttpHeaders = null;
		let temptest=this._cookieService.get('jwt');
		if(temptest){
			headers=new HttpHeaders({jwt:temptest});
		}else{
			headers=new HttpHeaders();
		}
		headers.append('Content-Type','application/json;charset=utf-8');
		return headers;
	};

	// 将对象转换为json字符串
	toJSONStr(obj:any):string {
		if(obj == null) return '';

		if (typeof obj === 'string') {
			return obj;
		}
		if (typeof obj === 'object'){
			return JSON.stringify(obj);
		}
		return '';
	}

	// 错误处理
	handleError<T>(result?: T) {
	  	return (error: any): Observable<T> => {
	    	this.errorHandler.handleError(error);
	    	let data = new Observable<T>(
			    observer =>{  
			        setTimeout(() =>{
			            observer.next(result);
			        }, -1);    
			    }
			);
	  		return data;
	  	};
	}
}
